package com.xquant.marketdata.curvestrip.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.github.pagehelper.PageInfo;
import com.xquant.common.core.constant.ErrMsgConstant;
import com.xquant.common.core.exception.ServiceException;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.marketdata.curvestrip.domain.DivIrCurveDTO;
import com.xquant.marketdata.curvestrip.domain.VolsurfaceDTO;
import com.xquant.marketdata.curvestrip.entity.TvolsurfaceRatesDTO;
import com.xquant.marketdata.curvestrip.mapper.VolatilityCurveStripMapper;
import com.xquant.marketdata.curvestrip.service.VolatilityCurveStripService;
import com.xquant.marketdata.utils.DateUtils;
import com.xquant.marketdata.utils.ResponseVo;
import com.xquant.marketdata.utils.SortUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author yunnuo.yang
 * @Date 2020/9/22 10:00
 * @Description
 **/
@Service(VolatilityCurveStripService.BEAN_NAME)
public class VolatilityCurveStripServiceImpl implements VolatilityCurveStripService {


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private VolatilityCurveStripMapper volatilityCurveMapper;


    @Override
    public PageInfo<VolsurfaceDTO> queryVolatilityCurveByPage(Map<String, Object> param) {
        List<VolsurfaceDTO> list = volatilityCurveMapper.queryVolatilityCurveDTOByPage(param);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public void deleteVolatilityCurve(Map<String, Object> param) {
        volatilityCurveMapper.deleteVolatilityCurve(param);
        volatilityCurveMapper.deleteVolSurfaceRates(param);
        //删除用户和部门权限表数据
        removeUserPermSurface(param);
        removeDeptPermSurface(param);
        //删除读写权限表数据
        removeUserSurfaceByVlsCode(param);
        removeDeptSurfaceByVlsCode(param);
    }

    @Override
    public void insertVolatilityCurve(Map<String, Object> param) {
        volatilityCurveMapper.insertVolatilityCurve(param);
    }

    @Override
    public void updateVolatilityCurve(Map<String, Object> param) {
        volatilityCurveMapper.updateVolatilityCurve(param);
    }

    @Override
    public PageInfo<Map> queryVolatilityCurveRefSetByPage(Map<String, Object> param) {
        if (StringUtils.isBlank(MapUtils.getString(param, "refSetDate"))) {//不影响查询条件，给前端返回日期
            param.put("refSetDateN", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).toString());
        } else {
            param.put("refSetDateN", MapUtils.getString(param, "refSetDate"));
        }
        List<Map> list = volatilityCurveMapper.queryVolatilityCurveRefSetByPage(param);
        return new PageInfo<>(list);
    }

    @Override
    public void insertVolatilityCurveRefSet(Map<String, Object> param) {
        volatilityCurveMapper.insertVolatilityCurveRefSet(param);
    }

    @Override
    public void deleteVolatilityCurveRefSetByDate(Map<String, Object> param) {
        volatilityCurveMapper.deleteVolatilityCurveRefSetByDate(param);
    }

    @Override
    public void updateVolatilityCurveRefSet(Map<String, Object> param) {
        volatilityCurveMapper.updateVolatilityCurveRefSet(param);
    }

    @Override
    public List<Map> queryVolSurfaceRates(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.queryVolSurfaceRates(param);
        return list;
    }
    @Override
    public List<Map> getLastDateByVlsCode(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.getLastDateByVlsCode(param);
        return list;
    }

    @Override
    public boolean insertVolSurfaceRatesList(List<TvolsurfaceRatesDTO> list) {
        try{
            volatilityCurveMapper.insertVolSurfaceRatesList(list);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public List<Map> queryRealTimeVolSurfaceRates(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.queryRealTimeVolSurfaceRates(param);
        if (!list.isEmpty() && null != list.get(0).get("vls_delta")) {
            List<Map> list1 = SortUtil.sortTerm(list, "vls_term", true);
            sortVlsDelta(list1);
            FilterResult(list1);
            return list1;
        }
        return list;
    }


    @Override
    public void deleteVolSurfaceRates(Map<String, Object> param) {
        volatilityCurveMapper.deleteVolSurfaceRates(param);
    }

    @Override
    public void deleteVolSurfaceRatesList(Map<String,Set<String>> map) {
        map.keySet().stream().forEach(vlist->{
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("vlsCode",vlist);
            Set<String> dateList = map.get(vlist);
            hashMap.put("list",dateList);
            volatilityCurveMapper.deleteVolSurfaceRatesList(hashMap);
        });
    }

    @Override
    public void insertVolSurfaceRates(Map<String, Object> param) {
        volatilityCurveMapper.insertVolSurfaceRates(param);
    }

    @Override
    public void updateVolSurfaceRates(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.queryVolSurfaceRates(param);
        param.put("vlsRate", MapUtils.getString(param, "newVlsRate"));
        if (list.size() != 1) {
            volatilityCurveMapper.insertVolSurfaceRates(param);
        } else {
            volatilityCurveMapper.updateVolSurfaceRates(param);
        }
    }

    /**
     * 对包含VLS_DELTA的值进行排序
     *
     * @return
     */
    public List<Map> sortVlsDelta(List<Map> list) {
        if (list.size() == 0) {
            return list;
        }
        list.sort(Comparator.comparing((Map a) -> (toComperStr(a.get("vls_delta"), a.get("vls_opt_type")))));

        //Collections.reverse(list);
        return list;
    }

    private int toComperStr(Object vlsDelta, Object opt_type) {
        if (opt_type == null) {
            return 0;
        }
        String type = vlsDelta.toString() + opt_type.toString();
        Integer compare = 0;
        switch (type) {
            case "":
                compare = 0;
                break;
            case "0.25C":
                compare = 1;
                break;
            case "0.25P":
                compare = 2;
                break;
            case "0.1C":
                compare = 3;
                break;
            case "0.1P":
                compare = 4;
                break;
            default:
                compare = 0;
                break;
        }
        return compare;
    }

    /**
     * 将百分比行权价保留四位小数，并返回要求的数据，显示百分比
     * 期限展示 1D，2W，1M，3M，6M，12M；行权价展示：80%，90%，95%，100%，105%，110%，120%；不作处理
     *
     * @return
     */
    public List<Map> FilterResult(List<Map> list) {
        if (list.size() == 0) {
            return list;
        }
//        List<Map> resultList=new ArrayList<>();
        for (Map map : list) {

            map.put("vls_strike", NumberUtil.round(Double.parseDouble(map.get("vls_strike").toString()) * 100, 4));


//            if(NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),80)==0||
//                    NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),90)==0||
//                    NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),100)==0||
//                    NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),105)==0||
//                    NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),110)==0||
//                    NumberUtil.compare(Double.parseDouble(map.get("VLS_STRIKE").toString()),120)==0){
//
//            }
        }
        return list;
    }

    /**
     *  包装波动率曲面结果集  将关键期限点按顺序处理
     * @param list
     * @return
     */
    public ResponseVo packageResult(List<Map> list){
        //20220624 botao.yu 从曲线定义中获取行权价点范围
        Map vlsCodeParam=new HashMap();
        JSONObject xmlJsonObj=new JSONObject();
        List<Double> coverPointList=new ArrayList<>();
        if(list.size()>0){
            vlsCodeParam.put("vlsCode",list.get(0).get("vls_code"));
            List<Map> vlsCodeMap=volatilityCurveMapper.queryVolatilityCurveByPage(vlsCodeParam);
            if(vlsCodeMap.size()>0){
                xmlJsonObj= XML.toJSONObject(vlsCodeMap.get(0).get("vls_param").toString());
                double min=Double.parseDouble(xmlJsonObj.getByPath("root.Parameter.KeyValues.VLS_FM_MIN.content").toString());
                double max=Double.parseDouble(xmlJsonObj.getByPath("root.Parameter.KeyValues.VLS_FM_MAX.content").toString());
                double interVal=Double.parseDouble(xmlJsonObj.getByPath("root.Parameter.KeyValues.VLS_FM_INTERVAL.content").toString());
                double startPoint=min;
                while(startPoint<=max){
                    coverPointList.add(startPoint);
                    startPoint=Double.parseDouble(String.valueOf(NumberUtil.round(startPoint+interVal,6)));
                }
            }
        }
        Map<Integer, String> dateMap = new HashMap<Integer, String>();
        String dateStr = "";
        for (Map m : list) {
            dateStr = MapUtil.getStr(m, "vls_term_st");
            if (StringUtils.isNotBlank(dateStr)) {
                if(dateStr.toUpperCase(Locale.ROOT).contains("W")){
                    m.put("vls_term",Integer.parseInt(dateStr.replace("W", ""))*7+"D");
                    dateMap.put(Integer.parseInt(dateStr.replace("W", ""))*7, MapUtil.getStr(m, "vls_term_st"));
                }else if(dateStr.toUpperCase(Locale.ROOT).contains("M")){
                    m.put("vls_term",Integer.parseInt(dateStr.replace("M", ""))*30+"D");
                    dateMap.put(Integer.parseInt(dateStr.replace("M", ""))*30, MapUtil.getStr(m, "vls_term_st"));
                }else if(dateStr.toUpperCase(Locale.ROOT).contains("Y")){
                    m.put("vls_term",Integer.parseInt(dateStr.replace("Y", ""))*365+"D");
                    dateMap.put(Integer.parseInt(dateStr.replace("Y", ""))*365, MapUtil.getStr(m, "vls_term_st"));
                }else {
                    dateStr=dateStr.toUpperCase(Locale.ROOT);
                    dateMap.put(Integer.parseInt(dateStr.replace("D", "")), MapUtil.getStr(m, "vls_term_st"));
                }
            }
        }
        List<Integer> pointList=new ArrayList<>();
        for(Integer key: dateMap.keySet()){
            pointList.add(key);
        }
        pointList.sort( Comparator.comparingInt(Integer::intValue));
        List<String> pointList2=new ArrayList<>();
        for (Integer day:pointList) {
            pointList2.add(MapUtil.getStr(dateMap,day));
        }
        logger.info("曲面定义覆盖点："+Arrays.toString(coverPointList.toArray()));
        logger.info("曲面定义覆盖点条数："+coverPointList.toArray());
        logger.info("曲面期限点："+Arrays.toString(pointList2.toArray()));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("pointList",pointList2);
        //在同期限中对行权价进行排序
        List<Map> resultList=new ArrayList<>();
        try {
            for (String limit : pointList2) {
                List<Map> point = new ArrayList<>();
                for (Map m : list) {
                    if (MapUtil.getStr(m, "vls_term_st").equals(limit)) {
                        point.add(m);
                    }
                }
                point.sort(Comparator.comparing((Map a) -> (Double.parseDouble(a.get("vls_strike").toString()))));
                logger.info("单个期限点条数："+point.size());
                logger.info("各个期限点数据按行权价排序"+Arrays.toString(point.toArray()));
                point.stream().forEach((Map a)-> {
                    a.put("vls_strike_st",NumberUtil.round(Double.parseDouble(a.get("vls_strike").toString()),8));
                });
                //如果节点返回了各个点的数据  则在这里覆盖返回的行权价格
                for (int i = 0; i < point.size(); i++) {
                    point.get(i).put("vls_strike_st", coverPointList.get(i));
                }
                resultList.addAll(point);
            }
        }catch(Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ServiceException(ErrMsgConstant.INTERFACE_VOLRATE);
        }
        if(resultList.size()>0&&resultList.get(0).get("effect_time")!=null){
            String time=resultList.get(0).get("effect_time").toString();
            time=time.length()==5?"0"+time:time;
            resultMap.put("effectTime",resultList.get(0).get("beg_date")+" "+time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4));
        }
        resultList.stream().forEach((Map a)-> {
                    a.put("vls_strike",NumberUtil.round(Double.parseDouble(a.get("vls_strike").toString()),8));
                });
        resultMap.put("resultList",resultList);
        ResponseVo rvo = new ResponseVo();
        rvo.setResult(resultMap);
        return rvo;
    }


    public List<Map> queryVolRateForCone(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.queryVolRateForCone(param);
        return list;
    }
    public List<Map> queryVolCone(Map<String, Object> param) {
        List<Map> list = volatilityCurveMapper.queryVolCone(param);
        list=SortUtil.sortTerm(list, "vls_term", true);
        list.stream().forEach(map -> map.put("vls_term",transgetDate(map.get("vls_term").toString())));
        return list;
    }
    public String transgetDate(String dateStr){
        if(dateStr.contains("D")){
            int cnt=Integer.parseInt(dateStr.substring(0,dateStr.lastIndexOf("D")));
            return cnt%30==0?(cnt%360==0?cnt/360+"Y":cnt/30+"M") :cnt/7+"W";
        }
        return dateStr;
    }

    @Override
    public List<TvolsurfaceRatesDTO> getLastVolSurfaceRates(Map<String, Set<String>> map,List<TvolsurfaceRatesDTO> list) {
        map.keySet().stream().forEach(vls->{
            TreeSet<String> set = new TreeSet<>(((o1,o2)->o1.compareTo(o2)));
            set.addAll(map.get(vls));

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("vlsCode",vls);
            hashMap.put("begDate",set.first());
            volatilityCurveMapper.updateVolSurfaceRatesByBegDate(hashMap);

            HashMap<String, Object> hashMap2 = new HashMap<>();
            hashMap2.put("vlsCode",vls);
            hashMap2.put("endDate",set.last());
            String nextDate = volatilityCurveMapper.getNextDay(hashMap2);
            if (nextDate != null) {
                list.stream().filter(data ->
                        data.getVlsCode().equals(vls)&&data.getBegDate().equals(set.last())
                ).forEach(data -> {
                    data.setEndDate(nextDate);
                    data.setImpTime(DateUtil.now());
                    data.setVlsOptStyle("1");
                    data.setVlsDeltaType("1");
                    data.setVlsOptType("P");
                });
            }else{
                list.stream().forEach(data -> {
                    data.setEndDate("2050-12-31");
                    data.setImpTime(DateUtil.now());
                    data.setVlsOptStyle("1");
                    data.setVlsDeltaType("1");
                    data.setVlsOptType("P");
                });
            }

        });
        return list;
    }

    @Override
    public void deleteVolatilityCurveOne(TvolsurfaceRatesDTO tvolsurfaceRatesDTO) {

    }

    @Override
    public boolean insertVolSurfaceRates2(TvolsurfaceRatesDTO form) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("vlsCode",form.getVlsCode());
        hashMap.put("vlsTermSt",form.getVlsTermSt().toUpperCase(Locale.ROOT));

        hashMap.put("begDate",form.getBegDate());
        hashMap.put("vlsStrike",form.getVlsStrike());
        volatilityCurveMapper.updateVolSurfaceRatesByBegDate(hashMap);

        HashMap<String, Object> hashMap2 = new HashMap<>();
        hashMap2.put("vlsCode",form.getVlsCode());
        hashMap2.put("vlsTermSt",form.getVlsTermSt().toUpperCase(Locale.ROOT));
//        hashMap2.put("vlsTerm",form.getVlsTerm());
        hashMap2.put("vlsStrike",form.getVlsStrike());
        hashMap2.put("endDate",form.getBegDate());
        String nextDate = volatilityCurveMapper.getNextDay(hashMap2);
        if (nextDate != null) {
            form.setEndDate(nextDate);
        }
        hashMap2.put("begDate",form.getBegDate());
        volatilityCurveMapper.deleteVolSurfaceRates(hashMap2);
        List<TvolsurfaceRatesDTO> list = new ArrayList<>();
        list.add(form);
        return this.insertVolSurfaceRatesList(list);
    }

    @Override
    public void updateVolSurfaceRate(TvolsurfaceRatesDTO form) {
        volatilityCurveMapper.updateVolSurfaceRate(form);
    }


    @Override
    @Transactional
    public void allocateVolSurface(Map<String, Object> param) {
        /*****************************权限部分*****************************************/
        ArrayList<String> userPerms = new ArrayList<>();
        ArrayList<String> deptPerms = new ArrayList<>();
        /** 为读写表赋权*/
        //存放创建人所属部门和上级部门，必须写权限
        ArrayList<String> deptAncestors = new ArrayList<>();
        //存放其他部门
        ArrayList<String> anotherDepts = new ArrayList<>();
        //存放其他人的数组
        ArrayList<String> anotherUser = new ArrayList<>();

        Map<String,Object> deptCfgRights = new HashMap<>();
        Map<String,Object> anotherDeptCfgRights = new HashMap<>();
        String allocateDeptAndUsers = param.get("allocateDeptAndUser").toString();
        String userId = String.valueOf(SecurityUtils.getUserId());
        String vlsCode = String.valueOf(param.get("vlsCode"));
        String vlsRight = String.valueOf(param.get("vlsRight"));
        HashMap map= com.alibaba.fastjson2.JSONObject.parseObject( vlsRight,HashMap.class);
        //创建人所属部门
        String createDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId().toString();
        deptAncestors.add(createDeptId);
        //将创建人所属部门的上级部门加入deptPerms
        String deptAncestorIds = volatilityCurveMapper.getDeptAncestors(createDeptId);
        List<String> deptAncestorIdArrs = Arrays.asList(deptAncestorIds.split(","));
        for (String deptAncestorArr : deptAncestorIdArrs) {
            if ("0".equals(deptAncestorArr) != true) {
                deptPerms.add(deptAncestorArr);
                deptAncestors.add(deptAncestorArr);
            }
        }
        for (String allocateDeptAndUser : allocateDeptAndUsers.split(",")) {
            if (allocateDeptAndUser.charAt(0) == 'u') {
                userPerms.add(allocateDeptAndUser.substring(2));
                if(!userId.equals(allocateDeptAndUser.substring(2))){
                    //不是本人，赋予传过来的权限
                    anotherUser.add(allocateDeptAndUser.substring(2));
                }
            } else if (allocateDeptAndUser.charAt(0) == 'd') {
                deptPerms.add(allocateDeptAndUser.substring(2));
                if(!createDeptId.equals(allocateDeptAndUser.substring(2))){
                    //不是所属部门，赋予传过来的权限
                    anotherDepts.add(allocateDeptAndUser.substring(2));
                }
            }
        }
        // param中放入用户id和部门id，用于后续的tsys_user_perm和tsys_dept_perm
        if (userPerms.size() > 0) {
            param.put("userIds", userPerms);
        }
        if (deptPerms.size() > 0) {
            param.put("deptIds", deptPerms);
        }
        //为创建人单独赋写权限
        List<VolsurfaceDTO>  anotherUserList=new ArrayList<>();
        VolsurfaceDTO userCfgRights=new VolsurfaceDTO();
        userCfgRights.setCreateBy(userId);
        userCfgRights.setVlsCode(vlsCode);
        userCfgRights.setVlsRight("2");
        anotherUserList.add(userCfgRights);
        //其他人传过来的权限
        if(anotherUser.size() != 0){
            for (String authId:anotherUser) {
                VolsurfaceDTO anotherSet=new VolsurfaceDTO();
                anotherSet.setCreateBy(authId);
                anotherSet.setVlsCode(vlsCode);
                anotherSet.setVlsRight(map.get(anotherSet.getCreateBy()).toString());
                anotherUserList.add(anotherSet);
            }
            insertUserSurfaceRight(anotherUserList);
        }
        //为所属部门和上级部门单独赋写权限
        deptCfgRights.put("deptIds",deptAncestors);
        deptCfgRights.put("vlsCode",vlsCode);
        deptCfgRights.put("vlsRight","2");
        insertDeptSurfaceRight(deptCfgRights);
        //为其他部门赋传过来的权限
        anotherDepts.removeAll(deptAncestors);
        if(anotherDepts.size() != 0){
            anotherDeptCfgRights.put("deptIds",anotherDepts);
            anotherDeptCfgRights.put("vlsCode",vlsCode);
            anotherDeptCfgRights.put("vlsRight","2");
            insertDeptSurfaceRight(anotherDeptCfgRights);
        }

        /** 更新tsys_usr_perm和tsys_dept_perm **/
        updateSurfaceUserPerm(param);
        updateSurfaceDeptPerm(param);
        /*******************************************************************************/
    }

    @Override
    public void updateSurfaceAuthority(Map<String, Object> params) {
        List<Integer> userIds = (List<Integer>) params.get("userIds");
        String vlsRight = String.valueOf(params.get("vlsRight"));
        String deptId = String.valueOf(params.get("deptId"));
        //存放上级部门
        ArrayList<String> deptAncestors = new ArrayList<>();
        //将创建人所属部门的上级部门加入deptPerms
        String deptAncestorIds = volatilityCurveMapper.getDeptAncestors(deptId);
        List<String> deptAncestorIdArrs = Arrays.asList(deptAncestorIds.split(","));
        for (String deptAncestorArr : deptAncestorIdArrs) {
            if ("0".equals(deptAncestorArr) != true) {
                deptAncestors.add(deptAncestorArr);
            }
        }
        for(Integer userId : userIds){
            Map<String,Object> param = new HashMap<>();
            param.put("userId",userId);
            param.put("vlsCode",params.get("vlsCode"));
            param.put("deptId",deptId);
            param.put("vlsRight",vlsRight);
            if("1".equals(volatilityCurveMapper.querySurfaceFlagByUserId(String.valueOf(userId)))){
                //如果tsys_user_flag为1，则改其部门权限
                List<Map> list = volatilityCurveMapper.querySurfaceDept(param);
                if (list.size() == 0 && !"0".equals(vlsRight)) {
                    //如果原来没有权限且需要权限，直接插入
                    volatilityCurveMapper.saveSurfaceDept(param);
                } else if(list.size() != 0 && !"0".equals(vlsRight)){
                    //如果原本有权限且不是无权限，则修改
                    volatilityCurveMapper.updateSurfaceDept(param);
                }else if(list.size() != 0 && "0".equals(vlsRight)){
                    //如果原本有权限且无权限，直接删除
                    volatilityCurveMapper.deleteSurfaceDept(param);
                }
                //修改对应dept_id的tsys_dept_perm，先清空
                removeDeptPermSurfaceByDeptId(param);
                if(!"0".equals(vlsRight)) {
                    //先给传过来的部门赋权
                    params.put("deptIds",Arrays.asList(deptId));
                    updateSurfaceDeptPerm(params);
                    //给传过来的部门的上级部门赋值
                    Map<String,Object> deptParams = new HashMap<>();
                    deptParams.put("deptIds",deptAncestors);
                    deptParams.put("vlsCode",params.get("vlsCode"));
                    deptParams.put("vlsRight",2);
                    for(String deId : deptAncestors){
                        deptParams.put("deptId",deId);
                        volatilityCurveMapper.deleteSurfaceDept(deptParams);
                        volatilityCurveMapper.saveSurfaceDept(deptParams);
                        removeDeptPermSurfaceByDeptId(deptParams);
                    }
                    if(deptAncestors.size()>0){
                        updateSurfaceDeptPerm(deptParams);
                    }
                }
            }else{
                //flag不为1，则直接修改对应用户
                List<Map> list = volatilityCurveMapper.querySurfaceUserPerm(param);
                if (list.size() == 0 && !"0".equals(vlsRight)) {
                    volatilityCurveMapper.saveSurfaceUser(param);
                } else if(list.size() != 0 && !"0".equals(vlsRight)){
                    volatilityCurveMapper.updateSurfaceUser(param);
                }else if(list.size() != 0 && "0".equals(vlsRight)){
                    volatilityCurveMapper.deleteSurfaceUser(param);
                }
                removeUserPermSurfaceByUserId(param);
            }
        }
        if(!"0".equals(vlsRight)) {
            updateSurfaceUserPerm(params);
        }
    }

    @Override
    public List<VolsurfaceDTO> queryVolSurfaceCombox(Map<String, Object> params) {
        return null;
    }

    public void insertUserSurfaceRight(List<VolsurfaceDTO>   map) {
        volatilityCurveMapper.batchInsertSurfaceUser(map);
    }

    public void insertDeptSurfaceRight(Map map) {
        volatilityCurveMapper.batchInsertSurfaceDept(map);
    }

    public void removeUserPermSurfaceByUserId(Map param) {
        volatilityCurveMapper.removeUserPermSurfaceByUserId(param);
    }

    public void removeDeptPermSurfaceByDeptId(Map param) {
        volatilityCurveMapper.removeDeptPermSurfaceByDeptId(param);
    }

    public void removeUserPermSurface(Map param) {
        volatilityCurveMapper.removeUserPermSurface(param);
    }

    public void removeDeptPermSurface(Map param) {
        volatilityCurveMapper.removeDeptPermSurface(param);
    }

    public void removeUserSurfaceByVlsCode(Map param){
        volatilityCurveMapper.removeUserSurfaceByVlsCode(param);
    }

    public void removeDeptSurfaceByVlsCode(Map param){
        volatilityCurveMapper.removeDeptSurfaceByVlsCode(param);
    }

    public void updateSurfaceUserPerm(Map<String, Object> params) {
        volatilityCurveMapper.updateUserPermSurface(params);
    }

    public void updateSurfaceDeptPerm(Map<String, Object> params) {
        volatilityCurveMapper.updateDeptPermSurface(params);
    }




    public List<VolsurfaceDTO> checkVolatilityCurve(Map<String, Object> params) {
        return volatilityCurveMapper.checkVolatilityCurve(params);
    }
}
